package com.favorite;

import java.util.*;

public class Solution1356 {
    public int[] sortByBits(int[] arr) {
        List<Integer> list = new ArrayList<>();
        for (int j : arr) {
            list.add(j);
        }
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer i1, Integer i2) {
                int i = bitCount(i1);
                int j = bitCount(i2);
                return i == j ? Integer.compare(i1, i2) : Integer.compare(i, j);
            }
        });
        for (int i = 0; i < arr.length; i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }

    public int bitCount(int x) {
        int count = 0;
        while (x != 0) {
            x &= x - 1;
            count++;
        }
        return count;
    }
}
